﻿using System;
using System.ComponentModel;
using System.IO;
using System.Media;
using System.Windows.Forms;
using Microsoft.DirectX.DirectSound;

namespace UpwardsTimeClock.Prototype
{
    public class SoundControl : StartableControlBase<Sound>
    {
        private Device _directXDevice;
        private SecondaryBuffer _directXBuffer;
        private bool _gotFile;

        public SoundControl(Sound config): base(config)
        {
        }

        public override void Initialize(Control.ControlCollection controls)
        {
            base.Initialize(controls);

            string soundFile = GetSoundFile();

            if (soundFile != null)
            {
                _gotFile = true;
                _directXDevice = new Device();
                _directXDevice.SetCooperativeLevel(Application.OpenForms[0].Handle, CooperativeLevel.Normal);
                _directXBuffer = new SecondaryBuffer(soundFile, _directXDevice);
            }
        }

        private string GetSoundFile()
        {
            string soundPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sounds");
            string soundFile = Program.BuildFilePath(soundPath, Config.SoundFile);
            return soundFile;
        }

        public override void Start()
        {
            base.Start();
            if (_gotFile)
            {
                if (_directXBuffer == null)
                {
                    string soundFile = GetSoundFile();
                    if (soundFile != null)
                    {
                        _directXBuffer = new SecondaryBuffer(soundFile, _directXDevice);
                    }
                }
                if (_directXBuffer != null)
                {
                    _directXBuffer.SetCurrentPosition(0);
                    _directXBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                if (_directXBuffer != null)
                {
                    if (_directXBuffer.Status.Playing)
                    {
                        _directXBuffer.Stop();
                    }
                    _directXBuffer.Dispose();
                }
            }
        }

        public override void Reset()
        {
            base.Reset();
            if (_directXBuffer != null && _directXBuffer.Status.Playing)
            {
                _directXBuffer.Stop();
            }
        }
    }
}
